<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\ClientController;
use App\Models\Common\Wechat;
use App\Models\Shop;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WechatRefundSuccessController extends ClientController
{
    /**
     * 退款成功通知
     * @return mixed
     */
    public function index()
    {
        $app = Wechat::payment();
        $response = $app->handleRefundedNotify(function ($message, $reqInfo, $fail) use ($app) {
            try{
                Log::debug('退款通知',['message'=>$message,'reqInfo'=>$reqInfo,'fail'=>$fail]);
                // 其中 $message['req_info'] 获取到的是加密信息
                // $reqInfo 为 message['req_info'] 解密后的信息
                // 你的业务逻辑...
                DB::beginTransaction();

                // refund_number
                $refund_number = $reqInfo['out_refund_no'];

                // 查找退款订单
                $refund = DB::table('laifei_refund')
                    ->where('refund_number','=',$refund_number)
                    ->lockForUpdate()
                    ->first();
                $refund = json_decode(json_encode($refund), true);

                // 查找退款单对应的订单
                $order = DB::table('laifei_orders')->where('order_id','=',$refund['order_id'])->lockForUpdate()->first();
                $order = json_decode(json_encode($order), true);

                // 如果退款单不存在或已经退款结束
                if(!$refund || $refund['status'] !== 1){
                    DB::rollBack();
                    return true; // 告诉微信，我已经处理完了或者订单没找到，别再通知我了
                }

                // 接收成功信息验证
                if ($message['return_code'] !== 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    Log::info('退款失败:', ['$message' => $message, '$fail' => $fail]);
                    DB::rollBack();
                    return $fail('通信失败，请稍后再通知我');
                }

                // 再重新查询一次退款状态，确认已经退款成功
                $result = $app->refund->queryByOutRefundNumber($refund_number);
                Log::debug('退款查询',$result);
                if($result['return_code'] === 'FAIL'){ //通信失败
                    DB::rollBack();
                    return $fail('通信失败');
                }
                // 退款处理中
                if($result['refund_status_0'] === 'PROCESSING'){
                    DB::rollBack();
                    return $fail('退款处理中');
                }

                // 退款成功或失败，都要做处理
                if($result['refund_status_0'] === 'SUCCESS'){ // 退款成功
                    // 修改这个退款单的状态
                    DB::table('laifei_refund')->where('refund_number','=',$refund_number)->update([
                        'status'=>2,
                        'refund_at'=>$result['refund_success_time_0'],//退款成功时间
                    ]);
                    // 修改订单余额
                    DB::table('laifei_orders')->where('order_id','=',$refund['order_id'])->update([
                        'refund_fee' => (($order['refund_fee'] * 100) + $refund['refund_fee'] ) / 100.00,
                        'refund_num' => $order['refund_num'] + $refund['num'],
                    ]);
                } else{
                    // 修改这个退款单的状态
                    DB::table('laifei_refund')->where('refund_number','=',$refund_number)->update([
                        'status'=>3,
                    ]);
                    if($result['refund_status_0'] === 'REFUNDCLOSE'){
                        Log::debug('退款被关闭',$result);
                    } elseif($result['refund_status_0'] === 'CHANGE'){
                        Log::emergency('退款被冻结,退款异常，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，可前往商户平台（pay.weixin.qq.com）-交易中心，手动处理此笔退款',$result);
                    } else {
                        Log::emergency('退款异常',$result);
                    }
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                Log::emergency(WechatRefundSuccessController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
                return $fail('处理失败，已通知研发紧急处理');
            }

            // 继续处理完成退款单
            Shop::applyFinish($refund['apply_id']);


            return true; // 返回 true 告诉微信“我已处理完成”
            // 或返回错误原因 $fail('参数格式校验错误');
        });

        return $response;
    }


}
